﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Recognition;
using System.Windows;
using System.IO;

namespace B1103492
{
    /// <summary>
    /// 本类的打算是，只需要在调用该类的目的类中，
    /// 写自己的文本识别的
    ///                 speechRecognitionEngine.SpeechRecognized +=
    ///                new EventHandler<SpeechRecognizedEventArgs>
    ///                    (engine_SpeechRecognized);
    /// 与engine_SpeechRecognized类似的函数即可。
    /// 调用的方式可以查看MainWindow相应的调用模块。
    /// </summary>
    class SpeechToText
    {
        /// <summary>
        /// 参考代码：
        /// http://www.codeproject.com/Articles/380027/Csharp-Speech-to-Text 
        /// 有改动
        /// </summary>
        #region 自己变量

        private static SpeechRecognitionEngine speechRecognitionEngine = null;
        private static bool isWorking = false;
        #endregion

        public static EventHandler GetTextFromSpeech;

        #region 开始与关闭（对外接口）

        public static void Initialize(
            string[] Sets = null,
            RecognizeMode Mode = RecognizeMode.Single,
            string NationLanguage = "zh-CN")
        {
            try
            {
                speechRecognitionEngine =
                    createSpeechRecognitionEngine(NationLanguage);

                // 添加识别事件函数
                speechRecognitionEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(speechRecognitionEngine_SpeechRecognized);

                // load dictionary
                loadGrammar(Sets);

                // use the system's default microphone
                speechRecognitionEngine.SetInputToDefaultAudioDevice();

                // start listening
                speechRecognitionEngine.RecognizeAsync(Mode);
            }
            catch { }
        }


        public static void Start()
        {
            isWorking = true;
        }

        public static void End()
        {
            isWorking = false;
        }

        #endregion

        #region 内部函数


        private static void speechRecognitionEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            if (isWorking)
                if (GetTextFromSpeech != null)
                    GetTextFromSpeech(e.Result.Text, null);
        }

        private static SpeechRecognitionEngine
            createSpeechRecognitionEngine
            (string preferredCulture)
        {
            foreach (RecognizerInfo config in SpeechRecognitionEngine.InstalledRecognizers())
            {
                if (config.Culture.ToString() == preferredCulture)
                {
                    speechRecognitionEngine = new SpeechRecognitionEngine(config);
                    break;
                }
            }

            // if the desired culture is not found, then load default
            if (speechRecognitionEngine == null)
            {
                speechRecognitionEngine = new SpeechRecognitionEngine(SpeechRecognitionEngine.InstalledRecognizers()[0]);
            }

            return speechRecognitionEngine;
        }

        private static void loadGrammar(string[] sets)
        {
            if (sets == null)
            {
                // Create and load a dictation grammar.
                speechRecognitionEngine.LoadGrammar(new DictationGrammar());
                return;
            }
            try
            {
                Choices texts = new Choices();
                foreach (string line in sets)
                {
                    texts.Add(line.Trim());
                }
                Grammar wordsList = new Grammar
                    (new GrammarBuilder(texts));
                speechRecognitionEngine.LoadGrammar(wordsList);
            }
            catch (Exception)
            {
                // Create and load a dictation grammar.
                speechRecognitionEngine.LoadGrammar
                    (new DictationGrammar());
            }
        }

        #endregion
    }
}
